//
//  UIAlertView+Block.m
//  bottleMessage
//
//  Created by mazm on 14-12-19.
//  Copyright (c) 2014年 SnailGame.com. All rights reserved.
//

#import "NSTimerBlock.h"
#import <objc/runtime.h>

@interface NSTimerBlock ()
{
  
}

@property (nonatomic,strong) NSTimer *timer;
@end

@implementation  NSTimerBlock

@synthesize schBlock,timeCounts;
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

/**
 OC中的关联就是在已有类的基础上添加对象参数。来扩展原有的类，需要引入#import <objc/runtime.h>头文件。关联是基于一个key来区分不同的关联。
 常用函数: objc_setAssociatedObject     设置关联
 objc_getAssociatedObject     获取关联
 objc_removeAssociatedObjects 移除关联
 */

+ (NSTimerBlock *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti  scheduledBlock:(scheduledBlock) block
{
    NSTimerBlock *timeB = [[NSTimerBlock alloc] init];
    timeB.schBlock = block;
    timeB.timeCounts = 0;
    timeB.timeInterval = ti;
    timeB.timer = [NSTimer scheduledTimerWithTimeInterval:ti target:timeB selector:@selector(TimerSchedule:) userInfo:nil repeats:YES];
    return timeB;
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)dealloc
{
    self.timer = nil;
    self.schBlock = nil;
    self.timeCounts = 0;
}

/***/
-(void) invalidate
{
    if(self.timer)
    {
        [self.timer invalidate];
        self.timer = nil;
        self.timeCounts = 0;
        self.schBlock = nil;
    }
}

-(void) fire
{
    if(self.timer)
    {
        [self.timer fire];
    }
    else
    {
        self.timeCounts = 0;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:self.timeInterval target:self selector:@selector(TimerSchedule:) userInfo:nil repeats:YES];
    }
}


-(void) TimerSchedule:(NSTimer *)aTimer
{
    self.timeCounts ++;
    self.schBlock(self);
    if(self.timeCounts >= 100)
    {
        self.timeCounts = 0;
        [aTimer invalidate];
        self.timer = nil;
        if(self.lastScheduledBlock)
        {
            self.lastScheduledBlock();
        }
    }
}

/*
+(void) TimerSchedule:(NSTimer *)aTimer
{
    NSTimerBlock *timeB = (NSTimerBlock *)aTimer.userInfo;
    timeB.timeCounts ++;
    timeB.schBlock(aTimer);
    if(timeB.timeCounts >= 100)
    {
        timeB.timeCounts = 0;
        [aTimer invalidate];
        timeB.timer = nil;
        if(timeB.lastScheduledBlock)
        {
            timeB.lastScheduledBlock();
        }
    }
}*/




@end